package com.lzh.thinkpet.controller;

import com.lzh.thinkpet.model.Admin;
import com.lzh.thinkpet.service.AdminService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

/**
 * @author lzh
 * @date 2019/1/21 - 19:31
 */
@Controller
@RequestMapping("/gms")
public class IndexController {
    //定义一个全局的记录器，通过LoggerFactory获取

    private final static Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private AdminService adminService;


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toIndex() {
        return "login";
    }

    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public String doLogin(String uname, String upass, String uyzm, HttpSession session, Model model) {
        String yzm = (String) session.getAttribute("rand");
        if (!StringUtils.equalsIgnoreCase(yzm, uyzm)) {
            logger.info("验证码错误");
            model.addAttribute("msg", "验证码错误！");
            return "login";
        } else if (!adminService.existsThisAname(uname)) {
            logger.info("用户名"+uname+"不存在");
            model.addAttribute("msg", "用户名不存在！");
            return "login";
        } else if (!adminService.isTrueThisApass(uname,upass)){
            logger.info("密码错误");
            model.addAttribute("msg", "密码错误！");
            return "login";
        }else {
            logger.info("!!!用户 "+uname+" 登录成功");
            session.setAttribute("loginSession",uname);
            return "home";
        }

    }



    @RequestMapping("/home")
    public String toHome() {
        return "home";
    }

    @RequestMapping("/test")
    public String toInx() {
        return "test";
    }


    @RequestMapping("/select")
    public String toSelect() {
        return "select";
    }

    @RequestMapping("/doSelect")
    public String doSelect(ServletRequest request, ServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String id = request.getParameter("id");
        Admin admin = adminService.selectByPrimaryKey(Integer.parseInt(id));
        request.setAttribute("ad", admin);
        return "ok";
    }
}
